package com.huawei.housekeeper.config.filter;

import com.huawei.housekeeper.enums.ErrorCode;
import com.huawei.housekeeper.result.Result;
import com.huawei.housekeeper.utils.JsonUtil;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 未认证，自定义的返回结果
 */
@Component
@RefreshScope
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setHeader("Access-Control-Expose-Headers", "Authorization, Metis-Role");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.getWriter().println(JsonUtil.objectToJson(Result.createResult(ErrorCode.TOKEN_ERROR)));
        response.setStatus(401); // Aspect无法 处理 Adapter中错误 Adapter先执行
        response.getWriter().flush();
        response.flushBuffer();
    }
}